using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using SG3L_RAG.Application.Interfaces;
using SG3L_RAG.Domain.Entities;
using SG3L_RAG.Infrastructure.Persistence;

namespace SG3L_RAG.Api.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class StatisticsController : ControllerBase
    {
        private readonly IStatisticsService _statisticsService;
        private readonly SG3LDbContext _context;

        public StatisticsController(IStatisticsService statisticsService, SG3LDbContext context)
        {
            _statisticsService = statisticsService;
            _context = context;
        }

        /// <summary>
        /// 获取实时仪表盘统计数据
        /// </summary>
        [HttpGet("dashboard")]
        public async Task<ActionResult<DashboardStats>> GetDashboardStats()
        {
            try
            {
                var today = DateTime.UtcNow.Date;
                var tomorrow = today.AddDays(1);

                var stats = new DashboardStats
                {
                    TotalUsers = await _context.Users.CountAsync(),
                    TotalDocuments = await _context.Documents.CountAsync(),
                    TotalConversations = await _context.Conversations.CountAsync(),
                    TotalMessages = await _context.Messages.CountAsync(),
                    TotalDocumentChunks = await _context.DocumentChunks.CountAsync(),
                    ActiveUsersToday = await _context.Users
                        .Where(u => u.CreatedAt >= today && u.CreatedAt < tomorrow)
                        .CountAsync(),
                    DocumentsUploadedToday = await _context.Documents
                        .Where(d => d.CreatedAt >= today && d.CreatedAt < tomorrow)
                        .CountAsync(),
                    ConversationsToday = await _context.Conversations
                        .Where(c => c.CreatedAt >= today && c.CreatedAt < tomorrow)
                        .CountAsync(),
                    MessagesExchangedToday = await _context.Messages
                        .Where(m => m.CreatedAt >= today && m.CreatedAt < tomorrow)
                        .CountAsync()
                };

                return Ok(stats);
            }
            catch (Exception ex)
            {
                return BadRequest($"获取统计数据失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 获取用户统计
        /// </summary>
        [HttpGet("users")]
        public async Task<ActionResult<object>> GetUserStats()
        {
            try
            {
                var today = DateTime.UtcNow.Date;
                var tomorrow = today.AddDays(1);
                var weekAgo = today.AddDays(-7);
                var monthAgo = today.AddDays(-30);

                var totalUsers = await _context.Users.CountAsync();
                var newUsersToday = await _context.Users
                    .Where(u => u.CreatedAt >= today && u.CreatedAt < tomorrow)
                    .CountAsync();
                var newUsersThisWeek = await _context.Users
                    .Where(u => u.CreatedAt >= weekAgo)
                    .CountAsync();
                var newUsersThisMonth = await _context.Users
                    .Where(u => u.CreatedAt >= monthAgo)
                    .CountAsync();

                return Ok(new
                {
                    totalUsers,
                    newUsersToday,
                    newUsersThisWeek,
                    newUsersThisMonth
                });
            }
            catch (Exception ex)
            {
                return BadRequest($"获取用户统计失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 获取文档统计
        /// </summary>
        [HttpGet("documents")]
        public async Task<ActionResult<object>> GetDocumentStats()
        {
            try
            {
                var monthAgo = DateTime.UtcNow.Date.AddDays(-30);

                var totalDocuments = await _context.Documents.CountAsync();
                var totalChunks = await _context.DocumentChunks.CountAsync();
                var documentsThisMonth = await _context.Documents
                    .Where(d => d.CreatedAt >= monthAgo)
                    .CountAsync();
                var averageChunksPerDoc = totalDocuments > 0 ? (double)totalChunks / totalDocuments : 0;

                return Ok(new
                {
                    totalDocuments,
                    totalChunks,
                    documentsThisMonth,
                    averageChunksPerDocument = Math.Round(averageChunksPerDoc, 2)
                });
            }
            catch (Exception ex)
            {
                return BadRequest($"获取文档统计失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 获取对话统计
        /// </summary>
        [HttpGet("conversations")]
        public async Task<ActionResult<object>> GetConversationStats()
        {
            try
            {
                var monthAgo = DateTime.UtcNow.Date.AddDays(-30);

                var totalConversations = await _context.Conversations.CountAsync();
                var totalMessages = await _context.Messages.CountAsync();
                var conversationsThisMonth = await _context.Conversations
                    .Where(c => c.CreatedAt >= monthAgo)
                    .CountAsync();
                var averageMessagesPerConv = totalConversations > 0 ? (double)totalMessages / totalConversations : 0;

                return Ok(new
                {
                    totalConversations,
                    totalMessages,
                    conversationsThisMonth,
                    averageMessagesPerConversation = Math.Round(averageMessagesPerConv, 2)
                });
            }
            catch (Exception ex)
            {
                return BadRequest($"获取对话统计失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 获取每日统计趋势（最近7天）
        /// </summary>
        [HttpGet("trends/daily")]
        public async Task<ActionResult<object>> GetDailyTrends()
        {
            try
            {
                var trends = new List<object>();

                for (int i = 6; i >= 0; i--)
                {
                    var day = DateTime.UtcNow.Date.AddDays(-i);
                    var nextDay = day.AddDays(1);

                    var documentsCount = await _context.Documents
                        .Where(d => d.CreatedAt >= day && d.CreatedAt < nextDay)
                        .CountAsync();
                    
                    var conversationsCount = await _context.Conversations
                        .Where(c => c.CreatedAt >= day && c.CreatedAt < nextDay)
                        .CountAsync();

                    var messagesCount = await _context.Messages
                        .Where(m => m.CreatedAt >= day && m.CreatedAt < nextDay)
                        .CountAsync();

                    trends.Add(new
                    {
                        date = day.ToString("yyyy-MM-dd"),
                        documents = documentsCount,
                        conversations = conversationsCount,
                        messages = messagesCount
                    });
                }

                return Ok(trends);
            }
            catch (Exception ex)
            {
                return BadRequest($"获取趋势统计失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 根据ID获取统计数据
        /// </summary>
        [HttpGet("{id}")]
        public async Task<ActionResult<Statistics>> GetStatistics(Guid id)
        {
            var statistics = await _statisticsService.GetByIdAsync(id);
            if (statistics == null)
            {
                return NotFound($"统计数据 {id} 不存在");
            }
            return Ok(statistics);
        }

        /// <summary>
        /// 根据类型获取统计数据列表
        /// </summary>
        [HttpGet("type/{statType}")]
        public async Task<ActionResult<IEnumerable<Statistics>>> GetStatisticsByType(string statType)
        {
            var statistics = await _statisticsService.GetByTypeAsync(statType);
            return Ok(statistics);
        }

        /// <summary>
        /// 获取指定类型的最新统计数据
        /// </summary>
        [HttpGet("type/{statType}/latest")]
        public async Task<ActionResult<Statistics>> GetLatestStatistics(string statType)
        {
            var statistics = await _statisticsService.GetLatestByTypeAsync(statType);
            if (statistics == null)
            {
                return NotFound($"类型 {statType} 的统计数据不存在");
            }
            return Ok(statistics);
        }

        /// <summary>
        /// 创建新的统计数据
        /// </summary>
        [HttpPost]
        public async Task<ActionResult<Statistics>> CreateStatistics([FromBody] CreateStatisticsRequest request)
        {
            try
            {
                var statistics = await _statisticsService.CreateAsync(request.StatType, request.StatValue);
                return CreatedAtAction(nameof(GetStatistics), new { id = statistics.Id }, statistics);
            }
            catch (Exception ex)
            {
                return BadRequest($"创建统计数据失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 更新统计数据
        /// </summary>
        [HttpPut("{id}")]
        public async Task<IActionResult> UpdateStatistics(Guid id, [FromBody] Statistics statistics)
        {
            if (id != statistics.Id)
            {
                return BadRequest("统计数据ID不匹配");
            }

            try
            {
                await _statisticsService.UpdateAsync(statistics);
                return NoContent();
            }
            catch (Exception ex)
            {
                return BadRequest($"更新统计数据失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 删除统计数据
        /// </summary>
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteStatistics(Guid id)
        {
            try
            {
                await _statisticsService.DeleteAsync(id);
                return NoContent();
            }
            catch (Exception ex)
            {
                return BadRequest($"删除统计数据失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 创建用户数量统计
        /// </summary>
        [HttpPost("user-count")]
        public async Task<ActionResult<Statistics>> CreateUserCount([FromBody] CreateCountRequest request)
        {
            try
            {
                var statistics = await _statisticsService.CreateUserCountAsync(request.Count);
                return CreatedAtAction(nameof(GetStatistics), new { id = statistics.Id }, statistics);
            }
            catch (Exception ex)
            {
                return BadRequest($"创建用户统计失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 创建文档数量统计
        /// </summary>
        [HttpPost("document-count")]
        public async Task<ActionResult<Statistics>> CreateDocumentCount([FromBody] CreateCountRequest request)
        {
            try
            {
                var statistics = await _statisticsService.CreateDocumentCountAsync(request.Count);
                return CreatedAtAction(nameof(GetStatistics), new { id = statistics.Id }, statistics);
            }
            catch (Exception ex)
            {
                return BadRequest($"创建文档统计失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 创建对话数量统计
        /// </summary>
        [HttpPost("conversation-count")]
        public async Task<ActionResult<Statistics>> CreateConversationCount([FromBody] CreateCountRequest request)
        {
            try
            {
                var statistics = await _statisticsService.CreateConversationCountAsync(request.Count);
                return CreatedAtAction(nameof(GetStatistics), new { id = statistics.Id }, statistics);
            }
            catch (Exception ex)
            {
                return BadRequest($"创建对话统计失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 创建消息数量统计
        /// </summary>
        [HttpPost("message-count")]
        public async Task<ActionResult<Statistics>> CreateMessageCount([FromBody] CreateCountRequest request)
        {
            try
            {
                var statistics = await _statisticsService.CreateMessageCountAsync(request.Count);
                return CreatedAtAction(nameof(GetStatistics), new { id = statistics.Id }, statistics);
            }
            catch (Exception ex)
            {
                return BadRequest($"创建消息统计失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 增加统计数值
        /// </summary>
        [HttpPost("type/{statType}/increment")]
        public async Task<IActionResult> IncrementStat(string statType)
        {
            try
            {
                await _statisticsService.IncrementStatAsync(statType);
                return NoContent();
            }
            catch (Exception ex)
            {
                return BadRequest($"增加统计失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 减少统计数值
        /// </summary>
        [HttpPost("type/{statType}/decrement")]
        public async Task<IActionResult> DecrementStat(string statType)
        {
            try
            {
                await _statisticsService.DecrementStatAsync(statType);
                return NoContent();
            }
            catch (Exception ex)
            {
                return BadRequest($"减少统计失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 更新统计数值
        /// </summary>
        [HttpPut("type/{statType}/value")]
        public async Task<IActionResult> UpdateStatValue(string statType, [FromBody] UpdateStatValueRequest request)
        {
            try
            {
                await _statisticsService.UpdateStatValueAsync(statType, request.NewValue);
                return NoContent();
            }
            catch (Exception ex)
            {
                return BadRequest($"更新统计数值失败: {ex.Message}");
            }
        }
    }

    // 请求模型
    public class CreateStatisticsRequest
    {
        public string StatType { get; set; } = string.Empty;
        public int StatValue { get; set; }
    }

    public class CreateCountRequest
    {
        public int Count { get; set; }
    }

    public class UpdateStatValueRequest
    {
        public int NewValue { get; set; }
    }

    // 仪表盘统计数据模型
    public class DashboardStats
    {
        public int TotalUsers { get; set; }
        public int TotalDocuments { get; set; }
        public int TotalConversations { get; set; }
        public int TotalMessages { get; set; }
        public int TotalDocumentChunks { get; set; }
        public int ActiveUsersToday { get; set; }
        public int DocumentsUploadedToday { get; set; }
        public int ConversationsToday { get; set; }
        public int MessagesExchangedToday { get; set; }
    }
}
